{{template "member/top.html" .}}
<div class="m-b-md"> 
	<h3 class="m-b-none">
		{{if .isNew}}
			{{msg $ "addTheme"}}
		{{else}}
			{{msg $ "updateTheme"}}
		- 
		{{.theme.Name}}
		{{end}}
		<a class="btn btn-default" href="/preview?themeId={{.themeId}}" target="_blank"><span class="fa fa-eye"></span> {{msg . "preview"}}</a>
		
		<small>
		
		<a target="_blank" href="https://github.com/leanote/leanote/wiki/leanote-blog-theme-api">{{msg . "needHelp"}} {{msg . "Leanote Blog Theme Api"}}</a>
		</small>
	</h3>
</div>

<style>
#tplContent * {
	font-family: Monaco, Menlo, 'Ubuntu Mono', Consolas, source-code-pro, monospace;
}
.image-list {
	list-style: none;
	padding: 0;
}
.image-list li {
	display: inline-block;
	margin-right: 5px;
	text-align: center;
}
.image-list li .thumb {
	width: 100px;
	height: 100px;
	line-height: 100px;
	overflow: hidden;
	border: 1px solid #ccc;
	padding: 3px;
	border-radius: 5px;
}
.op {
	text-align: center;
}
</style>
<div class="row">
<div class="col-sm-4">
	<section class="panel panel-default">
		<header class="panel-heading">
			{{msg . "tplStyleScript"}}:
		</header>
		<div class="panel-body" style="<!--height:430px;-->overflow: auto;">
	
	<div class="list-group bg-white file-list">
		{{range .myTpls}}
		<a href="#" class="list-group-item " data-file="{{.}}"> 
			<i class="fa fa-remove icon-muted remove-file" title="delete file" ></i> 
			<span class="filename" data-filename="{{.}}">{{.}}</span>
			<span class="badge"></span>
		</a>
		{{end}}
		
		</div>
	</div>
	<footer class="panel-footer text-right bg-light lter">
		<a class="btn btn-default" id="newFile">{{msg . "newFile"}}</a>
	</footer>
	</section>
</div>

<div class="col-sm-8">
	<section class="panel panel-default">
		<header class="panel-heading">
			{{msg . "currentFile"}}: <span id="curTpl">header.html</span>
			<span id="msg"></span>
		</header>
		<div class="panel-body">
			<div id="tplContent" class="form-control" style="width: 100%; height: 500px;"></div>
		</div>
		<footer class="panel-footer text-right bg-light lter">
		    <button type="submit" id="saveBtn" class="btn btn-success">{{msg . "save"}}</button>
		</footer>
	</section>
</div>
</div>

<div class="row">
<div class="col-sm-12">
	<section class="panel panel-default">
		<header class="panel-heading">
			{{msg . "image"}}: images/
		</header>
		<div class="panel-body">
			<ul class="image-list" id="imageList">
			</ul>
		</div>
		<footer class="panel-footer text-right bg-light lter">
			<form id="formLogo" action="/member/blog/uploadThemeImage" method="post"
				enctype="multipart/form-data" target="logoTarget">
				<input type="hidden" name="themeId" value="{{.themeId}}" />
				<input type="file" class="form-control" id="logo2" name="file"
					onChange='$("#formLogo").submit();' /> 
			</form>
			<iframe id="logoTarget" name="logoTarget" src="#" style="display: none"></iframe>
		</footer>
	</section>
</div>
</div>

{{template "member/footer.html" .}}
<script src="/public/libs/ace/ace.js"></script>
<script>
var editor = ace.edit("tplContent");
editor.setTheme("ace/theme/tomorrow");

var urlPrefix = "{{.siteUrl}}";
var userId = "{{.userInfo.UserId.Hex}}";
var themeId = "{{.themeId}}";
var themeBasePath = "/{{$.theme.Path}}";
var theme = {
	cache: {}, // filename => content
	inited: {}, // filename => bool, 是否已初始化, 防止未加载完就切换到其它
	curTplO: $("#curTpl"),
	tplContentO: $("#tplContent"),
	saveBtnO: $("#saveBtn"),
	newFileO: $("#newFile"),
	curTpl: "",
	tplInfos: {"header.html": "{{msg . "header"}}", "footer.html": "{{msg . "footer"}}", "index.html": "{{msg . "index"}}", "cate.html": "{{msg . "cate"}}", "search.html": "{{msg . "search"}}", "single.html": "{{msg . "single"}}", "archive.html": "{{msg . "archive"}}", "post.html": "{{msg . "post"}}", "tags.html": "{{msg . "tags"}}", "tag_posts.html": "{{msg . "tag_posts"}}", "share_comment.html": "{{msg . "share_comment"}}", "404.html":"404", "theme.json": "{{msg . "themeJson"}}", "paging.html": "{{msg . "paging"}}", "highlight.html": "{{msg . "highlight"}}"},
	init: function() {
		var self = this;
		self.showTplInfo();
		$(".file-list").on("click", "a", function() {
			$(".file-list a").removeClass("active");
			var filename = $(this).data('file');
			self.saveCurContent(); // 保存当前的
			self.renderTpl(filename); // 再渲染
			$(this).addClass("active");
		});
		
		self.renderTpl("header.html");
		$(".file-list a").eq(0).addClass("active");
		
		self.saveBtnO.click(function(){ 
			self.saveCurContent($(this));
		});
		
		self.removeFile();
		self.newFile();
		
		self.initImage();
	},
	removeFile: function() {
		var self = this;
		$(".file-list").on("click", ".remove-file", function(e) {
			e.stopPropagation();
			var $a = $(this).closest("a");
			var file = $a.data('file');
			art.confirm(getMsg("Are you sure to delete") + ' ' + file + " ?", function() {
				ajaxPost("/member/blog/deleteTpl", {themeId: themeId, filename: file}, function(re) {
					// if(reIsOk(re)) {
						art.tips(getMsg("Success"));
						$a.remove();
						if(self.curTpl == file) {
							$(".file-list a").eq(0).trigger("click");
						}
					//} else {
					//	art.alert(re.Msg);
					//}
				})
			});
		});
	},
	newFile: function() {
		var self = this;
		self.newFileO.click(function() {
			// 文件是否存在?
			
			art.prompt(getMsg("Filename"), function(file) { 
				if(!file) {
					return;
				}
				if($('[data-filename="' + file + '"]').length > 0) {
					art.alert(getMsg('File exists'));
					return;
				}
				var t = $('<a href="#" class="list-group-item " data-file="' + file + '"> <i class="fa fa-remove icon-muted remove-file" title="' + getMsg("Delete file") + '" ></i> <span class="filename" data-filename="' + file + '">' + file + '</span><span class="badge"></span></a>');
				$(".file-list").append(t);
				
				self.cache[file] = "";
				self.inited[file] = true;
				
				// trigger click, 选中之
				t.click();
			});
		});
	},
	showTplInfo: function() {
		var self = this;
		$(".file-list a").each(function() {
			var file = $(this).data("file");
			var info = "";
			info = self.tplInfos[file];
			if(!info) {
				if(file.indexOf(".css") > 0) {
					info = "{{msg . "style"}}";
				} else if(file.indexOf(".js") > 0) {
					info = "{{msg . "script"}}";
				}  else if(file.indexOf(".html") > 0) {
					info = "{{msg . "tpl"}}";
				}
			} else {
				$(this).find(".remove-file").remove();
			}
			$(this).find(".badge").text(info);
		});
	},
	msgO: $("#msg"),
	saveCurContent: function(t) {
		var self = this;
		var content = editor.getValue()
		
		var filename = self.curTpl;
		if(!filename) {
			return;
		}
		// 之前的内容是否有改动
		if(self.cache[filename] == content) {
			// console.log('content is same');
			return;
		}
		// 内容都没有加载进来
		if(!self.inited[filename]) {
			// console.log('not inited');
			return;
		}
		
		if(t) {
			t.button("loading");
		}
		self.msgO.html("...");
		ajaxPost("/member/blog/updateTplContent", {themeId: themeId, filename: self.curTpl, content: content}, function(re) {
			if(t) {
				t.button("reset");
			}
			if(reIsOk(re)) {
				self.cache[filename] = content;
				// art.tips("Success");
				self.msgO.html("{{msg . "saveSuccess"}}")
				setTimeout(function() {
					self.msgO.html("");
				}, 3000);
			} else {
				art.alert(re.Msg);
			}
		});
	},
	renderContent: function(name, content) {
		var self = this;
		self.curTplO.html(name);
		// self.curTpl = name; // 这里才设置
		var lang = "html";
		if(name.indexOf(".js") > 0 || name.indexOf(".json") > 0) {
			lang = "javascript";
		} else if(name.indexOf(".css") > 0) {
			lang = "css";
		}
		editor.setValue(content);
		editor.getSession().setUndoManager(new ace.UndoManager());
		editor.session.setMode("ace/mode/" + lang);
		editor.gotoLine(1);
		setTimeout(function() {
			editor.gotoLine(1);
		}, 200);
	},
	renderTpl: function(name) {
		var self = this;
		var content = "";
		self.curTpl = name; // 这里设置为空
		if(self.cache[name] != undefined) {
			content = self.cache[name];
			self.renderContent(name, content);
			return;
		}
		ajaxGet("/member/blog/getTplContent", {themeId: themeId, filename: name}, function(re){
			if(reIsOk(re)) {
				self.cache[name] = re.Item;
				self.inited[name] = true;
				// 以防点击过快, 响应不按顺序
				if (self.curTpl == name) {
					self.renderContent(name, re.Item);
				} else {
					alert(getMsg('Error'));
				}
			}
		});
	},
	
	//-----------------
	// theme images
	imageListO: $("#imageList"),
	initImage: function() {
		var self = this;
		self.reRenderImages();
		self.imageListO.on("click", ".delete-image", function(re) {
			var file = $(this).data('image');
			var t = this;
			art.confirm(getMsg("Are you sure to delete") + ' ' + file + " ?", function() {
				ajaxPost("/member/blog/deleteThemeImage", {themeId: themeId, filename: file}, function(re) {
					if(reIsOk(re)) {
						art.tips(getMsg("Success"));
						$(t).closest("li").remove();
					} else {
						art.alert(re.Msg);
					}
				});
			});
		});
	},
	renderImages: function(images) {
		var self = this;
		if(!images || images.length == 0) {
			self.imageListO.html(getMsg("No images"));
			return;
		}
		var html = "";
		for(var i = 0; i < images.length; ++i) {
			var image = images[i];
			var path = themeBasePath + "/images/" + image;
			
			html += '<li><div class="thumb"><img src="' + path + '"></div><div class="op"><span>' + image + '</span><br /><a class="btn btn-xs btn-warning delete-image" data-image="' + image + '"><span class="fa fa-remove"></span></a></div></li>';
		}
		self.imageListO.html(html);
	},
	reRenderImages: function() {
		var self = this;
		ajaxGet("/member/blog/listThemeImages", {themeId: themeId}, function(re) {
			if(reIsOk(re)) {
				var images = re.List;
				self.renderImages(images);
			}
		});
	},
}
$(function() {
	theme.init();
	$(window).keydown(function(e) {
		if (e.keyCode == 83 && (e.ctrlKey || e.metaKey)) {
			e.preventDefault();
			theme.saveBtnO.trigger("click");
		}
	});
});

// filename, result, resultCode
function uploadFinish(ret) {
	if (ret) {
		if (ret.resultCode == '1') {
			theme.reRenderImages();
			art.tips(ret.result)
			return;
		}
		art.alert(ret.result);
		return;
	}
	// 上传出错
	art.alert(getMsg("Error"));
}
</script>

{{template "member/end.html" .}}
